import {MenuOperationInfo, MenuTreeRes} from "@/interface/basicsInterface/systemManage/index.ts";
import {RouteRecordRaw} from "vue-router";
import router from "@/router";

const modules = import.meta.glob('../views/**/index.vue', {eager: false})
const initDynamicRouter = async (menuList: MenuTreeRes[], type: string): Promise<void> => {
    const routerList = await parseMenuListToRoutes("", menuList)
    if (!routerList) {
        console.error("路由初始化失败")
    }
    if (routerList.length == 0) {
        console.warn("路由初始化路由为空")
    }
    routerList.forEach((routerItem: RouteRecordRaw) => {
        router.addRoute(type, routerItem)
    })
}

async function parseMenuListToRoutes(parentFullPathName: String, menuList: MenuTreeRes[]): Promise<Array<RouteRecordRaw>> {
    let routerList: Array<RouteRecordRaw> = []
    for (const menuItem of menuList) {
        let vueModule: any | null = null;
        let nowLevelFullName = `${parentFullPathName} / ${menuItem.name}`
        if (menuItem.children.length != 0) {
            vueModule = await parseMenuListToRoutes(nowLevelFullName.replace("/", ""), menuItem.children)
            routerList = [...routerList, ...vueModule]
            continue
        }
        const vuePath = `../views${menuItem.fullPath}/index.vue`
        try {
            vueModule = await modules[vuePath]()
        } catch (e) {
            console.log(`vue加载失败:${vuePath}`, '错误：', e)
        }
        if (!vueModule) continue
        const routeRecord: RouteRecordRaw = {
            path: menuItem.fullPath,
            name: menuItem.name,
            meta: {
                title: nowLevelFullName.replace("/", ""),
                key: menuItem.menuId,
                iconTag: menuItem.iconTag,
                keepAlive: true
            },
            component: vueModule.default,
            children: []
        }
        routerList.push(routeRecord)
    }
    return routerList
}

export {
    initDynamicRouter
}

// 返回当前登录用户下绑定的角色的操作菜单
export function initUserRoleMenu(bindingMenu: MenuOperationInfo[], allMenuTreeList: MenuTreeRes[]) {
    let newPagesList: MenuTreeRes[] = []
    for (const menuItem of allMenuTreeList) {
        const hasBindingMenu = bindingMenu.find((bindingMenu => bindingMenu.menuId === menuItem.menuId))
        if (!hasBindingMenu) continue
        const newMenuItem: MenuTreeRes = {
            menuId: menuItem.menuId,
            name: menuItem.name,
            parentMenuId: menuItem.parentMenuId,
            nowPath: menuItem.nowPath,
            fullPath: menuItem.fullPath,
            iconTag: menuItem.iconTag,
            menuOrder: menuItem.menuOrder,
            children: []
        }
        if (menuItem.children.length != 0) {
            newMenuItem.children = initUserRoleMenu(bindingMenu, menuItem.children)
        }
        newPagesList.push(newMenuItem)
    }
    return newPagesList
}

// 得到用户可以操作的菜单，拿出菜单路径
export function byAllMenuGetPath(allPagesList: MenuTreeRes[]) {
    let newPagesList: Array<string> = []
    allPagesList.forEach((item: MenuTreeRes) => {
        if (item.children.length == 0) {
            newPagesList.push(item.fullPath)
        } else {
            item.children.forEach((childItem: any) => {
                newPagesList.push(childItem.fullPath)
            })
        }
    })
    return newPagesList
}
